package com.touwowo.eight;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.touwowo.utils.RabbitMqUtils;

import java.util.HashMap;
import java.util.Map;

public class Consumer01 {
    private static final String NORMAL_EXCHANGE = "normal_exchange";
    private static final String DEAD_EXCHANGE = "dead_exchange";
    private static final String NORMAL_QUEUE = "normal_queue";
    private static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //声明交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        // 设置死信队列参数设置
        Map<String,Object> arguments = new HashMap<>();
        // 设置死信消息的路由设置
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key","to_dead");
        // arguments.put("x-max-length",5);
        // 设置普通队列，并传入设置的参数
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);
        // 设置死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"to_dead");

        //队列与交换机绑定
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"normal");
        DeliverCallback callback = (consumerTag, message) -> {
            String msg = new String(message.getBody());
            if("Producer5".equals(msg)){
                System.out.println(msg+"：消息被拒绝");
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else {
                System.out.println("Consumer01收到的消息为："+msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
        };
        channel.basicConsume(NORMAL_QUEUE,false,callback,consumerTag -> {});
    }
}
